home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / codecs.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  36KB  |  1,068 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. ''' codecs -- Python Codec Registry, API and helpers.
  5.  
  6.  
  7. Written by Marc-Andre Lemburg (mal@lemburg.com).
  8.  
  9. (c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
  10.  
  11. '''
  12. import __builtin__
  13. import sys
  14.  
  15. try:
  16.     from _codecs import *
  17. except ImportError:
  18.     why = None
  19.     raise SystemError('Failed to load the builtin codecs: %s' % why)
  20.  
  21. __all__ = [
  22.     'register',
  23.     'lookup',
  24.     'open',
  25.     'EncodedFile',
  26.     'BOM',
  27.     'BOM_BE',
  28.     'BOM_LE',
  29.     'BOM32_BE',
  30.     'BOM32_LE',
  31.     'BOM64_BE',
  32.     'BOM64_LE',
  33.     'BOM_UTF8',
  34.     'BOM_UTF16',
  35.     'BOM_UTF16_LE',
  36.     'BOM_UTF16_BE',
  37.     'BOM_UTF32',
  38.     'BOM_UTF32_LE',
  39.     'BOM_UTF32_BE',
  40.     'strict_errors',
  41.     'ignore_errors',
  42.     'replace_errors',
  43.     'xmlcharrefreplace_errors',
  44.     'register_error',
  45.     'lookup_error']
  46. BOM_UTF8 = '\xef\xbb\xbf'
  47. BOM_LE = BOM_UTF16_LE = '\xff\xfe'
  48. BOM_BE = BOM_UTF16_BE = '\xfe\xff'
  49. BOM_UTF32_LE = '\xff\xfe\x00\x00'
  50. BOM_UTF32_BE = '\x00\x00\xfe\xff'
  51. if sys.byteorder == 'little':
  52.     BOM = BOM_UTF16 = BOM_UTF16_LE
  53.     BOM_UTF32 = BOM_UTF32_LE
  54. else:
  55.     BOM = BOM_UTF16 = BOM_UTF16_BE
  56.     BOM_UTF32 = BOM_UTF32_BE
  57. BOM32_LE = BOM_UTF16_LE
  58. BOM32_BE = BOM_UTF16_BE
  59. BOM64_LE = BOM_UTF32_LE
  60. BOM64_BE = BOM_UTF32_BE
  61.  
  62. class CodecInfo(tuple):
  63.     
  64.     def __new__(cls, encode, decode, streamreader = None, streamwriter = None, incrementalencoder = None, incrementaldecoder = None, name = None):
  65.         self = tuple.__new__(cls, (encode, decode, streamreader, streamwriter))
  66.         self.name = name
  67.         self.encode = encode
  68.         self.decode = decode
  69.         self.incrementalencoder = incrementalencoder
  70.         self.incrementaldecoder = incrementaldecoder
  71.         self.streamwriter = streamwriter
  72.         self.streamreader = streamreader
  73.         return self
  74.  
  75.     
  76.     def __repr__(self):
  77.         return '<%s.%s object for encoding %s at 0x%x>' % (self.__class__.__module__, self.__class__.__name__, self.name, id(self))
  78.  
  79.  
  80.  
  81. class Codec:
  82.     """ Defines the interface for stateless encoders/decoders.
  83.  
  84.         The .encode()/.decode() methods may use different error
  85.         handling schemes by providing the errors argument. These
  86.         string values are predefined:
  87.  
  88.          'strict' - raise a ValueError error (or a subclass)
  89.          'ignore' - ignore the character and continue with the next
  90.          'replace' - replace with a suitable replacement character;
  91.                     Python will use the official U+FFFD REPLACEMENT
  92.                     CHARACTER for the builtin Unicode codecs on
  93.                     decoding and '?' on encoding.
  94.          'xmlcharrefreplace' - Replace with the appropriate XML
  95.                                character reference (only for encoding).
  96.          'backslashreplace'  - Replace with backslashed escape sequences
  97.                                (only for encoding).
  98.  
  99.         The set of allowed values can be extended via register_error.
  100.  
  101.     """
  102.     
  103.     def encode(self, input, errors = 'strict'):
  104.         """ Encodes the object input and returns a tuple (output
  105.             object, length consumed).
  106.  
  107.             errors defines the error handling to apply. It defaults to
  108.             'strict' handling.
  109.  
  110.             The method may not store state in the Codec instance. Use
  111.             StreamCodec for codecs which have to keep state in order to
  112.             make encoding/decoding efficient.
  113.  
  114.             The encoder must be able to handle zero length input and
  115.             return an empty object of the output object type in this
  116.             situation.
  117.  
  118.         """
  119.         raise NotImplementedError
  120.  
  121.     
  122.     def decode(self, input, errors = 'strict'):
  123.         """ Decodes the object input and returns a tuple (output
  124.             object, length consumed).
  125.  
  126.             input must be an object which provides the bf_getreadbuf
  127.             buffer slot. Python strings, buffer objects and memory
  128.             mapped files are examples of objects providing this slot.
  129.  
  130.             errors defines the error handling to apply. It defaults to
  131.             'strict' handling.
  132.  
  133.             The method may not store state in the Codec instance. Use
  134.             StreamCodec for codecs which have to keep state in order to
  135.             make encoding/decoding efficient.
  136.  
  137.             The decoder must be able to handle zero length input and
  138.             return an empty object of the output object type in this
  139.             situation.
  140.  
  141.         """
  142.         raise NotImplementedError
  143.  
  144.  
  145.  
  146. class IncrementalEncoder(object):
  147.     '''
  148.     An IncrementalEncoder encodes an input in multiple steps. The input can be
  149.     passed piece by piece to the encode() method. The IncrementalEncoder remembers
  150.     the state of the Encoding process between calls to encode().
  151.     '''
  152.     
  153.     def __init__(self, errors = 'strict'):
  154.         '''
  155.         Creates an IncrementalEncoder instance.
  156.  
  157.         The IncrementalEncoder may use different error handling schemes by
  158.         providing the errors keyword argument. See the module docstring
  159.         for a list of possible values.
  160.         '''
  161.         self.errors = errors
  162.         self.buffer = ''
  163.  
  164.     
  165.     def encode(self, input, final = False):
  166.         '''
  167.         Encodes input and returns the resulting object.
  168.         '''
  169.         raise NotImplementedError
  170.  
  171.     
  172.     def reset(self):
  173.         '''
  174.         Resets the encoder to the initial state.
  175.         '''
  176.         pass
  177.  
  178.     
  179.     def getstate(self):
  180.         '''
  181.         Return the current state of the encoder.
  182.         '''
  183.         return 0
  184.  
  185.     
  186.     def setstate(self, state):
  187.         '''
  188.         Set the current state of the encoder. state must have been
  189.         returned by getstate().
  190.         '''
  191.         pass
  192.  
  193.  
  194.  
  195. class BufferedIncrementalEncoder(IncrementalEncoder):
  196.     '''
  197.     This subclass of IncrementalEncoder can be used as the baseclass for an
  198.     incremental encoder if the encoder must keep some of the output in a
  199.     buffer between calls to encode().
  200.     '''
  201.     
  202.     def __init__(self, errors = 'strict'):
  203.         IncrementalEncoder.__init__(self, errors)
  204.         self.buffer = ''
  205.  
  206.     
  207.     def _buffer_encode(self, input, errors, final):
  208.         raise NotImplementedError
  209.  
  210.     
  211.     def encode(self, input, final = False):
  212.         data = self.buffer + input
  213.         (result, consumed) = self._buffer_encode(data, self.errors, final)
  214.         self.buffer = data[consumed:]
  215.         return result
  216.  
  217.     
  218.     def reset(self):
  219.         IncrementalEncoder.reset(self)
  220.         self.buffer = ''
  221.  
  222.     
  223.     def getstate(self):
  224.         if not self.buffer:
  225.             pass
  226.         return 0
  227.  
  228.     
  229.     def setstate(self, state):
  230.         if not state:
  231.             pass
  232.         self.buffer = ''
  233.  
  234.  
  235.  
  236. class IncrementalDecoder(object):
  237.     '''
  238.     An IncrementalDecoder decodes an input in multiple steps. The input can be
  239.     passed piece by piece to the decode() method. The IncrementalDecoder
  240.     remembers the state of the decoding process between calls to decode().
  241.     '''
  242.     
  243.     def __init__(self, errors = 'strict'):
  244.         '''
  245.         Creates a IncrementalDecoder instance.
  246.  
  247.         The IncrementalDecoder may use different error handling schemes by
  248.         providing the errors keyword argument. See the module docstring
  249.         for a list of possible values.
  250.         '''
  251.         self.errors = errors
  252.  
  253.     
  254.     def decode(self, input, final = False):
  255.         '''
  256.         Decodes input and returns the resulting object.
  257.         '''
  258.         raise NotImplementedError
  259.  
  260.     
  261.     def reset(self):
  262.         '''
  263.         Resets the decoder to the initial state.
  264.         '''
  265.         pass
  266.  
  267.     
  268.     def getstate(self):
  269.         '''
  270.         Return the current state of the decoder.
  271.  
  272.         This must be a (buffered_input, additional_state_info) tuple.
  273.         buffered_input must be a bytes object containing bytes that
  274.         were passed to decode() that have not yet been converted.
  275.         additional_state_info must be a non-negative integer
  276.         representing the state of the decoder WITHOUT yet having
  277.         processed the contents of buffered_input.  In the initial state
  278.         and after reset(), getstate() must return (b"", 0).
  279.         '''
  280.         return ('', 0)
  281.  
  282.     
  283.     def setstate(self, state):
  284.         '''
  285.         Set the current state of the decoder.
  286.  
  287.         state must have been returned by getstate().  The effect of
  288.         setstate((b"", 0)) must be equivalent to reset().
  289.         '''
  290.         pass
  291.  
  292.  
  293.  
  294. class BufferedIncrementalDecoder(IncrementalDecoder):
  295.     '''
  296.     This subclass of IncrementalDecoder can be used as the baseclass for an
  297.     incremental decoder if the decoder must be able to handle incomplete byte
  298.     sequences.
  299.     '''
  300.     
  301.     def __init__(self, errors = 'strict'):
  302.         IncrementalDecoder.__init__(self, errors)
  303.         self.buffer = ''
  304.  
  305.     
  306.     def _buffer_decode(self, input, errors, final):
  307.         raise NotImplementedError
  308.  
  309.     
  310.     def decode(self, input, final = False):
  311.         data = self.buffer + input
  312.         (result, consumed) = self._buffer_decode(data, self.errors, final)
  313.         self.buffer = data[consumed:]
  314.         return result
  315.  
  316.     
  317.     def reset(self):
  318.         IncrementalDecoder.reset(self)
  319.         self.buffer = ''
  320.  
  321.     
  322.     def getstate(self):
  323.         return (self.buffer, 0)
  324.  
  325.     
  326.     def setstate(self, state):
  327.         self.buffer = state[0]
  328.  
  329.  
  330.  
  331. class StreamWriter(Codec):
  332.     
  333.     def __init__(self, stream, errors = 'strict'):
  334.         """ Creates a StreamWriter instance.
  335.  
  336.             stream must be a file-like object open for writing
  337.             (binary) data.
  338.  
  339.             The StreamWriter may use different error handling
  340.             schemes by providing the errors keyword argument. These
  341.             parameters are predefined:
  342.  
  343.              'strict' - raise a ValueError (or a subclass)
  344.              'ignore' - ignore the character and continue with the next
  345.              'replace'- replace with a suitable replacement character
  346.              'xmlcharrefreplace' - Replace with the appropriate XML
  347.                                    character reference.
  348.              'backslashreplace'  - Replace with backslashed escape
  349.                                    sequences (only for encoding).
  350.  
  351.             The set of allowed parameter values can be extended via
  352.             register_error.
  353.         """
  354.         self.stream = stream
  355.         self.errors = errors
  356.  
  357.     
  358.     def write(self, object):
  359.         """ Writes the object's contents encoded to self.stream.
  360.         """
  361.         (data, consumed) = self.encode(object, self.errors)
  362.         self.stream.write(data)
  363.  
  364.     
  365.     def writelines(self, list):
  366.         ''' Writes the concatenated list of strings to the stream
  367.             using .write().
  368.         '''
  369.         self.write(''.join(list))
  370.  
  371.     
  372.     def reset(self):
  373.         ''' Flushes and resets the codec buffers used for keeping state.
  374.  
  375.             Calling this method should ensure that the data on the
  376.             output is put into a clean state, that allows appending
  377.             of new fresh data without having to rescan the whole
  378.             stream to recover state.
  379.  
  380.         '''
  381.         pass
  382.  
  383.     
  384.     def __getattr__(self, name, getattr = getattr):
  385.         ''' Inherit all other methods from the underlying stream.
  386.         '''
  387.         return getattr(self.stream, name)
  388.  
  389.     
  390.     def __enter__(self):
  391.         return self
  392.  
  393.     
  394.     def __exit__(self, type, value, tb):
  395.         self.stream.close()
  396.  
  397.  
  398.  
  399. class StreamReader(Codec):
  400.     
  401.     def __init__(self, stream, errors = 'strict'):
  402.         """ Creates a StreamReader instance.
  403.  
  404.             stream must be a file-like object open for reading
  405.             (binary) data.
  406.  
  407.             The StreamReader may use different error handling
  408.             schemes by providing the errors keyword argument. These
  409.             parameters are predefined:
  410.  
  411.              'strict' - raise a ValueError (or a subclass)
  412.              'ignore' - ignore the character and continue with the next
  413.              'replace'- replace with a suitable replacement character;
  414.  
  415.             The set of allowed parameter values can be extended via
  416.             register_error.
  417.         """
  418.         self.stream = stream
  419.         self.errors = errors
  420.         self.bytebuffer = ''
  421.         self.charbuffer = ''
  422.         self.linebuffer = None
  423.  
  424.     
  425.     def decode(self, input, errors = 'strict'):
  426.         raise NotImplementedError
  427.  
  428.     
  429.     def read(self, size = -1, chars = -1, firstline = False):
  430.         ''' Decodes data from the stream self.stream and returns the
  431.             resulting object.
  432.  
  433.             chars indicates the number of characters to read from the
  434.             stream. read() will never return more than chars
  435.             characters, but it might return less, if there are not enough
  436.             characters available.
  437.  
  438.             size indicates the approximate maximum number of bytes to
  439.             read from the stream for decoding purposes. The decoder
  440.             can modify this setting as appropriate. The default value
  441.             -1 indicates to read and decode as much as possible.  size
  442.             is intended to prevent having to decode huge files in one
  443.             step.
  444.  
  445.             If firstline is true, and a UnicodeDecodeError happens
  446.             after the first line terminator in the input only the first line
  447.             will be returned, the rest of the input will be kept until the
  448.             next call to read().
  449.  
  450.             The method should use a greedy read strategy meaning that
  451.             it should read as much data as is allowed within the
  452.             definition of the encoding and the given size, e.g.  if
  453.             optional encoding endings or state markers are available
  454.             on the stream, these should be read too.
  455.         '''
  456.         if self.linebuffer:
  457.             self.charbuffer = ''.join(self.linebuffer)
  458.             self.linebuffer = None
  459.         
  460.         while True:
  461.             if chars < 0:
  462.                 if size < 0:
  463.                     if self.charbuffer:
  464.                         break
  465.                     
  466.                 elif len(self.charbuffer) >= size:
  467.                     break
  468.                 
  469.             elif len(self.charbuffer) >= chars:
  470.                 break
  471.             
  472.             if size < 0:
  473.                 newdata = self.stream.read()
  474.             else:
  475.                 newdata = self.stream.read(size)
  476.             data = self.bytebuffer + newdata
  477.             
  478.             try:
  479.                 (newchars, decodedbytes) = self.decode(data, self.errors)
  480.             except UnicodeDecodeError:
  481.                 exc = None
  482.                 if firstline:
  483.                     (newchars, decodedbytes) = self.decode(data[:exc.start], self.errors)
  484.                     lines = newchars.splitlines(True)
  485.                     if len(lines) <= 1:
  486.                         raise 
  487.                     len(lines) <= 1
  488.                 else:
  489.                     raise 
  490.                 firstline
  491.  
  492.             self.bytebuffer = data[decodedbytes:]
  493.             self.charbuffer += newchars
  494.             if not newdata:
  495.                 break
  496.                 continue
  497.             self
  498.         if chars < 0:
  499.             result = self.charbuffer
  500.             self.charbuffer = ''
  501.         else:
  502.             result = self.charbuffer[:chars]
  503.             self.charbuffer = self.charbuffer[chars:]
  504.         return result
  505.  
  506.     
  507.     def readline(self, size = None, keepends = True):
  508.         ''' Read one line from the input stream and return the
  509.             decoded data.
  510.  
  511.             size, if given, is passed as size argument to the
  512.             read() method.
  513.  
  514.         '''
  515.         readsize = self.linebuffer if self.linebuffer else 72
  516.         line = ''
  517.         while True:
  518.             data = self.read(readsize, firstline = True)
  519.             if data:
  520.                 if data.endswith('\r'):
  521.                     data += self.read(size = 1, chars = 1)
  522.                 
  523.             
  524.             line += data
  525.             lines = line.splitlines(True)
  526.             if lines:
  527.                 if len(lines) > 1:
  528.                     line = lines[0]
  529.                     del lines[0]
  530.                     if len(lines) > 1:
  531.                         lines[-1] += self.charbuffer
  532.                         self.linebuffer = lines
  533.                         self.charbuffer = None
  534.                     else:
  535.                         self.charbuffer = lines[0] + self.charbuffer
  536.                     if not keepends:
  537.                         line = line.splitlines(False)[0]
  538.                     
  539.                     break
  540.                 
  541.                 line0withend = lines[0]
  542.                 line0withoutend = lines[0].splitlines(False)[0]
  543.                 if line0withend != line0withoutend:
  544.                     self.charbuffer = ''.join(lines[1:]) + self.charbuffer
  545.                     if keepends:
  546.                         line = line0withend
  547.                     else:
  548.                         line = line0withoutend
  549.                     break
  550.                 
  551.             
  552.             if not data or size is not None:
  553.                 if line and not keepends:
  554.                     line = line.splitlines(False)[0]
  555.                 
  556.                 break
  557.             
  558.             if readsize < 8000:
  559.                 readsize *= 2
  560.                 continue
  561.         return line
  562.  
  563.     
  564.     def readlines(self, sizehint = None, keepends = True):
  565.         """ Read all lines available on the input stream
  566.             and return them as list of lines.
  567.  
  568.             Line breaks are implemented using the codec's decoder
  569.             method and are included in the list entries.
  570.  
  571.             sizehint, if given, is ignored since there is no efficient
  572.             way to finding the true end-of-line.
  573.  
  574.         """
  575.         data = self.read()
  576.         return data.splitlines(keepends)
  577.  
  578.     
  579.     def reset(self):
  580.         ''' Resets the codec buffers used for keeping state.
  581.  
  582.             Note that no stream repositioning should take place.
  583.             This method is primarily intended to be able to recover
  584.             from decoding errors.
  585.  
  586.         '''
  587.         self.bytebuffer = ''
  588.         self.charbuffer = u''
  589.         self.linebuffer = None
  590.  
  591.     
  592.     def seek(self, offset, whence = 0):
  593.         """ Set the input stream's current position.
  594.  
  595.             Resets the codec buffers used for keeping state.
  596.         """
  597.         self.reset()
  598.         self.stream.seek(offset, whence)
  599.  
  600.     
  601.     def next(self):
  602.         ''' Return the next decoded line from the input stream.'''
  603.         line = self.readline()
  604.         if line:
  605.             return line
  606.         raise StopIteration
  607.  
  608.     
  609.     def __iter__(self):
  610.         return self
  611.  
  612.     
  613.     def __getattr__(self, name, getattr = getattr):
  614.         ''' Inherit all other methods from the underlying stream.
  615.         '''
  616.         return getattr(self.stream, name)
  617.  
  618.     
  619.     def __enter__(self):
  620.         return self
  621.  
  622.     
  623.     def __exit__(self, type, value, tb):
  624.         self.stream.close()
  625.  
  626.  
  627.  
  628. class StreamReaderWriter:
  629.     ''' StreamReaderWriter instances allow wrapping streams which
  630.         work in both read and write modes.
  631.  
  632.         The design is such that one can use the factory functions
  633.         returned by the codec.lookup() function to construct the
  634.         instance.
  635.  
  636.     '''
  637.     encoding = 'unknown'
  638.     
  639.     def __init__(self, stream, Reader, Writer, errors = 'strict'):
  640.         ''' Creates a StreamReaderWriter instance.
  641.  
  642.             stream must be a Stream-like object.
  643.  
  644.             Reader, Writer must be factory functions or classes
  645.             providing the StreamReader, StreamWriter interface resp.
  646.  
  647.             Error handling is done in the same way as defined for the
  648.             StreamWriter/Readers.
  649.  
  650.         '''
  651.         self.stream = stream
  652.         self.reader = Reader(stream, errors)
  653.         self.writer = Writer(stream, errors)
  654.         self.errors = errors
  655.  
  656.     
  657.     def read(self, size = -1):
  658.         return self.reader.read(size)
  659.  
  660.     
  661.     def readline(self, size = None):
  662.         return self.reader.readline(size)
  663.  
  664.     
  665.     def readlines(self, sizehint = None):
  666.         return self.reader.readlines(sizehint)
  667.  
  668.     
  669.     def next(self):
  670.         ''' Return the next decoded line from the input stream.'''
  671.         return self.reader.next()
  672.  
  673.     
  674.     def __iter__(self):
  675.         return self
  676.  
  677.     
  678.     def write(self, data):
  679.         return self.writer.write(data)
  680.  
  681.     
  682.     def writelines(self, list):
  683.         return self.writer.writelines(list)
  684.  
  685.     
  686.     def reset(self):
  687.         self.reader.reset()
  688.         self.writer.reset()
  689.  
  690.     
  691.     def __getattr__(self, name, getattr = getattr):
  692.         ''' Inherit all other methods from the underlying stream.
  693.         '''
  694.         return getattr(self.stream, name)
  695.  
  696.     
  697.     def __enter__(self):
  698.         return self
  699.  
  700.     
  701.     def __exit__(self, type, value, tb):
  702.         self.stream.close()
  703.  
  704.  
  705.  
  706. class StreamRecoder:
  707.     ''' StreamRecoder instances provide a frontend - backend
  708.         view of encoding data.
  709.  
  710.         They use the complete set of APIs returned by the
  711.         codecs.lookup() function to implement their task.
  712.  
  713.         Data written to the stream is first decoded into an
  714.         intermediate format (which is dependent on the given codec
  715.         combination) and then written to the stream using an instance
  716.         of the provided Writer class.
  717.  
  718.         In the other direction, data is read from the stream using a
  719.         Reader instance and then return encoded data to the caller.
  720.  
  721.     '''
  722.     data_encoding = 'unknown'
  723.     file_encoding = 'unknown'
  724.     
  725.     def __init__(self, stream, encode, decode, Reader, Writer, errors = 'strict'):
  726.         ''' Creates a StreamRecoder instance which implements a two-way
  727.             conversion: encode and decode work on the frontend (the
  728.             input to .read() and output of .write()) while
  729.             Reader and Writer work on the backend (reading and
  730.             writing to the stream).
  731.  
  732.             You can use these objects to do transparent direct
  733.             recodings from e.g. latin-1 to utf-8 and back.
  734.  
  735.             stream must be a file-like object.
  736.  
  737.             encode, decode must adhere to the Codec interface, Reader,
  738.             Writer must be factory functions or classes providing the
  739.             StreamReader, StreamWriter interface resp.
  740.  
  741.             encode and decode are needed for the frontend translation,
  742.             Reader and Writer for the backend translation. Unicode is
  743.             used as intermediate encoding.
  744.  
  745.             Error handling is done in the same way as defined for the
  746.             StreamWriter/Readers.
  747.  
  748.         '''
  749.         self.stream = stream
  750.         self.encode = encode
  751.         self.decode = decode
  752.         self.reader = Reader(stream, errors)
  753.         self.writer = Writer(stream, errors)
  754.         self.errors = errors
  755.  
  756.     
  757.     def read(self, size = -1):
  758.         data = self.reader.read(size)
  759.         (data, bytesencoded) = self.encode(data, self.errors)
  760.         return data
  761.  
  762.     
  763.     def readline(self, size = None):
  764.         if size is None:
  765.             data = self.reader.readline()
  766.         else:
  767.             data = self.reader.readline(size)
  768.         (data, bytesencoded) = self.encode(data, self.errors)
  769.         return data
  770.  
  771.     
  772.     def readlines(self, sizehint = None):
  773.         data = self.reader.read()
  774.         (data, bytesencoded) = self.encode(data, self.errors)
  775.         return data.splitlines(1)
  776.  
  777.     
  778.     def next(self):
  779.         ''' Return the next decoded line from the input stream.'''
  780.         data = self.reader.next()
  781.         (data, bytesencoded) = self.encode(data, self.errors)
  782.         return data
  783.  
  784.     
  785.     def __iter__(self):
  786.         return self
  787.  
  788.     
  789.     def write(self, data):
  790.         (data, bytesdecoded) = self.decode(data, self.errors)
  791.         return self.writer.write(data)
  792.  
  793.     
  794.     def writelines(self, list):
  795.         data = ''.join(list)
  796.         (data, bytesdecoded) = self.decode(data, self.errors)
  797.         return self.writer.write(data)
  798.  
  799.     
  800.     def reset(self):
  801.         self.reader.reset()
  802.         self.writer.reset()
  803.  
  804.     
  805.     def __getattr__(self, name, getattr = getattr):
  806.         ''' Inherit all other methods from the underlying stream.
  807.         '''
  808.         return getattr(self.stream, name)
  809.  
  810.     
  811.     def __enter__(self):
  812.         return self
  813.  
  814.     
  815.     def __exit__(self, type, value, tb):
  816.         self.stream.close()
  817.  
  818.  
  819.  
  820. def open(filename, mode = 'rb', encoding = None, errors = 'strict', buffering = 1):
  821.     """ Open an encoded file using the given mode and return
  822.         a wrapped version providing transparent encoding/decoding.
  823.  
  824.         Note: The wrapped version will only accept the object format
  825.         defined by the codecs, i.e. Unicode objects for most builtin
  826.         codecs. Output is also codec dependent and will usually be
  827.         Unicode as well.
  828.  
  829.         Files are always opened in binary mode, even if no binary mode
  830.         was specified. This is done to avoid data loss due to encodings
  831.         using 8-bit values. The default file mode is 'rb' meaning to
  832.         open the file in binary read mode.
  833.  
  834.         encoding specifies the encoding which is to be used for the
  835.         file.
  836.  
  837.         errors may be given to define the error handling. It defaults
  838.         to 'strict' which causes ValueErrors to be raised in case an
  839.         encoding error occurs.
  840.  
  841.         buffering has the same meaning as for the builtin open() API.
  842.         It defaults to line buffered.
  843.  
  844.         The returned wrapped file object provides an extra attribute
  845.         .encoding which allows querying the used encoding. This
  846.         attribute is only available if an encoding was specified as
  847.         parameter.
  848.  
  849.     """
  850.     if encoding is not None and 'b' not in mode:
  851.         mode = mode + 'b'
  852.     
  853.     file = __builtin__.open(filename, mode, buffering)
  854.     if encoding is None:
  855.         return file
  856.     info = lookup(encoding)
  857.     srw = StreamReaderWriter(file, info.streamreader, info.streamwriter, errors)
  858.     srw.encoding = encoding
  859.     return srw
  860.  
  861.  
  862. def EncodedFile(file, data_encoding, file_encoding = None, errors = 'strict'):
  863.     """ Return a wrapped version of file which provides transparent
  864.         encoding translation.
  865.  
  866.         Strings written to the wrapped file are interpreted according
  867.         to the given data_encoding and then written to the original
  868.         file as string using file_encoding. The intermediate encoding
  869.         will usually be Unicode but depends on the specified codecs.
  870.  
  871.         Strings are read from the file using file_encoding and then
  872.         passed back to the caller as string using data_encoding.
  873.  
  874.         If file_encoding is not given, it defaults to data_encoding.
  875.  
  876.         errors may be given to define the error handling. It defaults
  877.         to 'strict' which causes ValueErrors to be raised in case an
  878.         encoding error occurs.
  879.  
  880.         The returned wrapped file object provides two extra attributes
  881.         .data_encoding and .file_encoding which reflect the given
  882.         parameters of the same name. The attributes can be used for
  883.         introspection by Python programs.
  884.  
  885.     """
  886.     if file_encoding is None:
  887.         file_encoding = data_encoding
  888.     
  889.     data_info = lookup(data_encoding)
  890.     file_info = lookup(file_encoding)
  891.     sr = StreamRecoder(file, data_info.encode, data_info.decode, file_info.streamreader, file_info.streamwriter, errors)
  892.     sr.data_encoding = data_encoding
  893.     sr.file_encoding = file_encoding
  894.     return sr
  895.  
  896.  
  897. def getencoder(encoding):
  898.     ''' Lookup up the codec for the given encoding and return
  899.         its encoder function.
  900.  
  901.         Raises a LookupError in case the encoding cannot be found.
  902.  
  903.     '''
  904.     return lookup(encoding).encode
  905.  
  906.  
  907. def getdecoder(encoding):
  908.     ''' Lookup up the codec for the given encoding and return
  909.         its decoder function.
  910.  
  911.         Raises a LookupError in case the encoding cannot be found.
  912.  
  913.     '''
  914.     return lookup(encoding).decode
  915.  
  916.  
  917. def getincrementalencoder(encoding):
  918.     """ Lookup up the codec for the given encoding and return
  919.         its IncrementalEncoder class or factory function.
  920.  
  921.         Raises a LookupError in case the encoding cannot be found
  922.         or the codecs doesn't provide an incremental encoder.
  923.  
  924.     """
  925.     encoder = lookup(encoding).incrementalencoder
  926.     if encoder is None:
  927.         raise LookupError(encoding)
  928.     encoder is None
  929.     return encoder
  930.  
  931.  
  932. def getincrementaldecoder(encoding):
  933.     """ Lookup up the codec for the given encoding and return
  934.         its IncrementalDecoder class or factory function.
  935.  
  936.         Raises a LookupError in case the encoding cannot be found
  937.         or the codecs doesn't provide an incremental decoder.
  938.  
  939.     """
  940.     decoder = lookup(encoding).incrementaldecoder
  941.     if decoder is None:
  942.         raise LookupError(encoding)
  943.     decoder is None
  944.     return decoder
  945.  
  946.  
  947. def getreader(encoding):
  948.     ''' Lookup up the codec for the given encoding and return
  949.         its StreamReader class or factory function.
  950.  
  951.         Raises a LookupError in case the encoding cannot be found.
  952.  
  953.     '''
  954.     return lookup(encoding).streamreader
  955.  
  956.  
  957. def getwriter(encoding):
  958.     ''' Lookup up the codec for the given encoding and return
  959.         its StreamWriter class or factory function.
  960.  
  961.         Raises a LookupError in case the encoding cannot be found.
  962.  
  963.     '''
  964.     return lookup(encoding).streamwriter
  965.  
  966.  
  967. def iterencode(iterator, encoding, errors = 'strict', **kwargs):
  968.     '''
  969.     Encoding iterator.
  970.  
  971.     Encodes the input strings from the iterator using a IncrementalEncoder.
  972.  
  973.     errors and kwargs are passed through to the IncrementalEncoder
  974.     constructor.
  975.     '''
  976.     encoder = getincrementalencoder(encoding)(errors, **kwargs)
  977.     for input in iterator:
  978.         output = encoder.encode(input)
  979.         if output:
  980.             yield output
  981.             continue
  982.     
  983.     output = encoder.encode('', True)
  984.     if output:
  985.         yield output
  986.     
  987.  
  988.  
  989. def iterdecode(iterator, encoding, errors = 'strict', **kwargs):
  990.     '''
  991.     Decoding iterator.
  992.  
  993.     Decodes the input strings from the iterator using a IncrementalDecoder.
  994.  
  995.     errors and kwargs are passed through to the IncrementalDecoder
  996.     constructor.
  997.     '''
  998.     decoder = getincrementaldecoder(encoding)(errors, **kwargs)
  999.     for input in iterator:
  1000.         output = decoder.decode(input)
  1001.         if output:
  1002.             yield output
  1003.             continue
  1004.     
  1005.     output = decoder.decode('', True)
  1006.     if output:
  1007.         yield output
  1008.     
  1009.  
  1010.  
  1011. def make_identity_dict(rng):
  1012.     ''' make_identity_dict(rng) -> dict
  1013.  
  1014.         Return a dictionary where elements of the rng sequence are
  1015.         mapped to themselves.
  1016.  
  1017.     '''
  1018.     res = { }
  1019.     for i in rng:
  1020.         res[i] = i
  1021.     
  1022.     return res
  1023.  
  1024.  
  1025. def make_encoding_map(decoding_map):
  1026.     ''' Creates an encoding map from a decoding map.
  1027.  
  1028.         If a target mapping in the decoding map occurs multiple
  1029.         times, then that target is mapped to None (undefined mapping),
  1030.         causing an exception when encountered by the charmap codec
  1031.         during translation.
  1032.  
  1033.         One example where this happens is cp875.py which decodes
  1034.         multiple character to \\u001a.
  1035.  
  1036.     '''
  1037.     m = { }
  1038.     for k, v in decoding_map.items():
  1039.         if v not in m:
  1040.             m[v] = k
  1041.             continue
  1042.         m[v] = None
  1043.     
  1044.     return m
  1045.  
  1046.  
  1047. try:
  1048.     strict_errors = lookup_error('strict')
  1049.     ignore_errors = lookup_error('ignore')
  1050.     replace_errors = lookup_error('replace')
  1051.     xmlcharrefreplace_errors = lookup_error('xmlcharrefreplace')
  1052.     backslashreplace_errors = lookup_error('backslashreplace')
  1053. except LookupError:
  1054.     strict_errors = None
  1055.     ignore_errors = None
  1056.     replace_errors = None
  1057.     xmlcharrefreplace_errors = None
  1058.     backslashreplace_errors = None
  1059.  
  1060. _false = 0
  1061. if _false:
  1062.     import encodings
  1063.  
  1064. if __name__ == '__main__':
  1065.     sys.stdout = EncodedFile(sys.stdout, 'latin-1', 'utf-8')
  1066.     sys.stdin = EncodedFile(sys.stdin, 'utf-8', 'latin-1')
  1067.  
  1068.